/* eslint-disable */
import { asyncRoutes, constantRoutes, setAsyncRoutes } from '@/router'
import store from '..'
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

export function generaAsyncRoutes(data) {
  // console.log(data)
  const routes = []

  data.forEach(item => {
    // console.log(item)
    // const url = `@/views/${item.url}`
    const menu = {
      path: item.path,
      component: item.url === '' ? Layout : (resolve) => require([`@/views/${item.url}`], resolve),
      // component: item.url === '' ? Layout : () => import ('@/views/dashboard/index'),
      hidden: item.hidden,
      alwaysShow: item.always_show,
      name: item.name,
      meta: item.meta
    }
    if (item.redirect) {
      menu.redirect = item.redirect
    }
    if (item.children) {
      menu.children = generaAsyncRoutes(item.children)
    }
    routes.push(menu)
  })
  // console.log(routes)

  return routes
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(async(resolve) => {
      // console.log(roles)

      // 获取动态路由，先判断动态路由是否为空，如果不为空则已获取
      if (!asyncRoutes || asyncRoutes.length <= 0) {
        const routes = await store.dispatch('user/getRoutes')

        const async_routes = routes ? generaAsyncRoutes(routes) : []
        // 最后添加404路由
        async_routes.push({ path: '*', redirect: '/404', hidden: true })
        setAsyncRoutes(async_routes)
        // console.log(asyncRoutes)
      }

      let accessedRoutes
      if (roles.includes('admin') || roles.includes('super_admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      // console.log(accessedRoutes)

      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
  // generateSyncRoutes({ commit }, data) {
  //   console.log(data)

  //   const async_routes = generaAsyncRoutes(data)
  //   setAsyncRoutes(async_routes)
  //   console.log(asyncRoutes)
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
